package com.cwt_taxi_xa;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.cwt_taxi_xa.db.bll.LocalInfoBiz;
import com.cwt_taxi_xa.model.LocalInfo;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.DecimalUtil;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.StringUtil;
import com.cwt_taxi_xa.util.Tools;
import com.cwt_taxi_xa.widget.timepicker.ScreenInfo;
import com.cwt_taxi_xa.widget.timepicker.WheelMain;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 收信箱信息界面
 *
 * @author ferch
 *
 */
public class BusinessDataOneDay extends CWTBaseActivity implements OnItemClickListener,
		OnTouchListener {
	private static final String TAG = "BusinessDataOneDay";
	public TextView tips;
	public ListView listView;
	public List<LocalInfo> list;
	private int lastItem;
	public View view;// 底部视图，加载更多
	TextView loadmore;
	public BusinessDataAdapter adapter;
	private LocalInfoBiz biz;
	String selectData = DateUtil.getTodayDate(DateUtil.df9);

	private TextView tv_count_all,tv_amount_all,tv_count_cash,tv_count_ykt,tv_count_union,
			tv_count_qr,tv_amount_cash,tv_amount_ykt,tv_amount_union,tv_amount_qr,tv_time,tv_type;
	private Button btn_date,btn_type;

	private WheelMain wheelMain;
	private Calendar calendar;
	private int year;
	private int month;
	private int day;
	private AlertDialog dialogTime;
	private AlertDialog dialogType;

	private String[] types = new  String[] {"全部", "现金", "M1卡交易" , "CPU卡交易","其他" };
	/**
	 * 0:全部
	 * 1：现金交易；
	 * 2：M1卡交易；
	 * 3：CPU卡交易；
	 * 4：其他
	 */
	/**
	 * 99:全部
	 * 0x00：现金交易；
	 * 0x01：M1卡交易；
	 * 0x03：CPU卡交易；
	 * 0x09：其他
	 */
	private int witch = 0;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.business_data_one_day);

		setupViews();
		addListener();
		initData();
	}

	private void addListener() {
		// TODO Auto-generated method stub
		listView.setOnItemClickListener(this);
		listView.setOnTouchListener(this);
		tips.setOnTouchListener(this);
		tv_type.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				doType();
			}
		});
		tv_time.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				doTime();
			}
		});
	}

	private void initData() {
		// TODO Auto-generated method stub
		tv_type.setText(types[witch]);
		String time = DateUtil.getTodayDate(DateUtil.df);
		tv_time.setText(time);
		queryMessageCenter();
	}

	private void setupViews() {
		// TODO Auto-generated method stub
		biz = LocalInfoBiz.getInstance();
		view = getLayoutInflater().inflate(R.layout.loadmore, null);
		tips = (TextView) this.findViewById(R.id.q_tip);
		listView = (ListView) this
				.findViewById(R.id.listView);
		listView.addFooterView(view);
		adapter = new BusinessDataAdapter(this);
		loadmore = (TextView)view.findViewById(R.id.moreText);

		tv_count_all = (TextView) this.findViewById(R.id.tv_count_all);
		tv_count_cash = (TextView) this.findViewById(R.id.tv_count_cash);
		tv_count_ykt = (TextView) this.findViewById(R.id.tv_count_ykt);
		tv_count_union = (TextView) this.findViewById(R.id.tv_count_union);
		tv_count_qr = (TextView) this.findViewById(R.id.tv_count_qr);
		tv_amount_all = (TextView) this.findViewById(R.id.tv_amount_all);
		tv_amount_cash = (TextView) this.findViewById(R.id.tv_amount_cash);
		tv_amount_ykt = (TextView) this.findViewById(R.id.tv_amount_ykt);
		tv_amount_union = (TextView) this.findViewById(R.id.tv_amount_union);
		tv_amount_qr = (TextView) this.findViewById(R.id.tv_amount_qr);
		tv_time = (TextView) this.findViewById(R.id.tv_time);
		tv_type = (TextView) this.findViewById(R.id.tv_type);

		btn_date = (Button) this.findViewById(R.id.btn_date);
		btn_type = (Button) this.findViewById(R.id.btn_type);
	}

	protected void doType() {
		// TODO Auto-generated method stub
		if(dialogType == null){
			dialogType = new  AlertDialog.Builder(this)
					.setTitle("账单类型" )
					.setIcon(android.R.drawable.ic_dialog_info)
					.setMultiChoiceItems(types,  null ,  null )
					.setSingleChoiceItems(types, witch, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int witch) {
							// TODO Auto-generated method stub
					/*if(witch == 0){
						witch = 99;
					}else if(witch == 1){
						witch = 0;
					}else if(witch == 1){
						witch = 1;
					}else if(witch == 1){
						witch = 3;
					}else if(witch == 1){
						witch = 9;
					}*/
							BusinessDataOneDay.this.witch = witch;
							tv_type.setText(types[witch]);
							dataCount();
							dialog.dismiss();
						}
					})
					.setNegativeButton("取消" ,  new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int arg1) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					})
					.show();
		}else{
			dialogType.show();
		}
	}

	/** 选择时间*/
	private void doTime() {
		// TODO Auto-generated method stub
		if(dialogTime == null){
			String title = "账单日期";
			LayoutInflater inflater = LayoutInflater.from(this);
			final View timepickerview = inflater.inflate(R.layout.datepicker,
					null);
			ScreenInfo screenInfo = new ScreenInfo(this);
			wheelMain = new WheelMain(timepickerview, false);
			wheelMain.screenheight = screenInfo.getHeight();

			calendar = Calendar.getInstance();
			if(!StringUtil.isNull(selectData)){
				try {
					Date date = DateUtil.df9.parse(selectData);
					calendar.setTime(date);
					year = calendar.get(Calendar.YEAR);
					month = calendar.get(Calendar.MONTH);
					day = calendar.get(Calendar.DAY_OF_MONTH);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			wheelMain.initDateTimePicker(year, month, day);
			wheelMain.setTextSize(28, 30);
			dialogTime = new AlertDialog.Builder(this)
					.setTitle(title)
					.setIcon(android.R.drawable.ic_dialog_info)
					.setView(timepickerview)
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String time = wheelMain.getTime();
							tv_time.setText(time);
							time = DateUtil.getTime(time, DateUtil.df, DateUtil.df9);
							if(!time.equals(selectData)){
								selectData = time;
								queryMessageCenter();
							}
							dialog.dismiss();
						}
					})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							}).show();
		}else{
			dialogTime.show();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/**
	 * 查找第一次的数据
	 */
	public void queryMessageCenter() {
		new AsyncTask<String, Integer, Long>() {
			@Override
			protected Long doInBackground(String... params) {
				list = biz.getOneDayBusinessInfo(selectData);
				return 1L;
			}

			@Override
			protected void onPostExecute(Long result) {
				dataCount();
			}
		}.execute();
	}
	protected void dataCount() {
		// TODO Auto-generated method stub
		int countAll,countCash = 0,countYkt = 0,countUnion = 0,countQr = 0;
		double amountAll = 0,amountCash = 0,amountYkt = 0,amountUnion = 0,amountQr = 0;
		ArrayList<LocalInfo> showList = null;
		if(list != null && list.size() != 0){
			showList = new ArrayList<LocalInfo>();
			for(int i = 0;i<list.size();i++){
				LocalInfo info = list.get(i);
				// 数据
				String data = info.getData();
				byte[] dataByte = Tools.yxReversal(Tools.parseHexStr2Byte(data));

				int amountIndex = 13 + 25 + 25 + 15 + 58;

				// 70	交易金额	BCD[3]	格式XXXXX.X元（总金额）
				BigDecimal decimal = new BigDecimal(Tools.bcd2Str(Tools.byteTobyte(dataByte, amountIndex, 3)));
				decimal = decimal.divide(new BigDecimal(10));
				double amount = decimal.doubleValue();

				//	78 	账单类型	BYTE
				int payType = Integer.parseInt(Tools.parseByte2HexStr(Tools.byteTobyte(dataByte, amountIndex + 7, 1)), 16);
				//0x00：现金交易；0x01：M1卡交易；0x03：CPU卡交易；0x09：其他
				if(payType == 0){// 现金
					if(witch == 0 || witch == 1){
						countCash++;
						amountCash += amount;
						showList.add(info);
					}
				}else if(payType == 1){// 一卡通
					if(witch == 0 || witch == 2){
						countYkt++;
						amountYkt += amount;
						showList.add(info);
					}
				}else if(payType == 3){// 闪付
					if(witch == 0 || witch == 3){
						countUnion++;
						amountUnion += amount;
						showList.add(info);
					}
				}else if(payType == 9){// 二维码
					if(witch == 0 || witch == 4){
						countQr++;
						amountQr += amount;
						showList.add(info);
					}
				}
			}
		}
		countAll = countCash + countQr + countUnion + countYkt;
		tv_count_all.setText(String.valueOf(countAll));
		tv_count_cash.setText(String.valueOf(countCash));
		tv_count_ykt.setText(String.valueOf(countYkt));
		tv_count_union.setText(String.valueOf(countUnion));
		tv_count_qr.setText(String.valueOf(countQr));

		amountAll = amountCash + amountQr + amountUnion + amountYkt;
		tv_amount_all.setText(DecimalUtil.priceFormat(amountAll));
		tv_amount_qr.setText(DecimalUtil.priceFormat(amountQr));
		tv_amount_cash.setText(DecimalUtil.priceFormat(amountCash));
		tv_amount_ykt.setText(DecimalUtil.priceFormat(amountYkt));
		tv_amount_union.setText(DecimalUtil.priceFormat(amountUnion));

		if (showList != null && showList.size() > 0) {
			tips.setVisibility(View.GONE);
			adapter.setData(showList);
			listView.setAdapter(adapter);
			listView.removeFooterView(view);
		} else {
			tips.setText("暂无数据!");
			tips.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 各个item点击事件
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new  Intent();
		//跳转到详细页面
		intent.setClass(BusinessDataOneDay.this, BusinessActivity.class);
		//把id传到详细页面，具体接受参照InvidationDetail，
		intent.putExtra("info", list.get(arg2));
		startActivity(intent);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(dialogTime != null && dialogTime.isShowing()){
			dialogTime.dismiss();
		}
		if(dialogType != null && dialogType.isShowing()){
			dialogType.dismiss();
		}
	}

	public class BusinessDataAdapter extends BaseAdapter{
		private static final String TAG = "BusinessDataAdapter";
		public Context context;
		private LayoutInflater mInflater=null;
		private List<LocalInfo> list;
		private LocalInfo localInfo;

		public BusinessDataAdapter(Context context) {
			this.context = context;
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			if(null!=list&&list.size()>0){
				return list.size();
			}

			return 0;
		}

		public void setData(List<LocalInfo> list) {
			this.list = list;
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		public void addItems(List<LocalInfo> nlist) {
			for (int i = 0; i < nlist.size(); i++) {
				this.list.add(nlist.get(i));
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			try {

				ViewHolder viewHolder = null;
				if(convertView == null){
					convertView = mInflater.inflate(R.layout.business_one_day_item, null);
					viewHolder = new ViewHolder();
					viewHolder.tv_empty_time = (TextView) convertView.findViewById(R.id.tv_empty_time);
					viewHolder.tv_load_time = (TextView) convertView.findViewById(R.id.tv_load_time);
					viewHolder.tv_car_times = (TextView) convertView.findViewById(R.id.tv_car_times);
					viewHolder.tv_pay_type = (TextView) convertView.findViewById(R.id.tv_pay_type);
					viewHolder.tv_amount = (TextView) convertView.findViewById(R.id.tv_amount);
					viewHolder.tv_amount_text = (TextView) convertView.findViewById(R.id.tv_amount_text);
					viewHolder.tv_create_time = (TextView) convertView.findViewById(R.id.tv_create_time);
					convertView.setTag(viewHolder);
				}else{
					viewHolder = (ViewHolder) convertView.getTag();
				}
				localInfo = list.get(position);
				String data = localInfo.getData();
				String dataCreateTime = localInfo.getTime();
				if(!StringUtil.isNull(dataCreateTime)){
					String createTime = DateUtil.getTime("20"+dataCreateTime, DateUtil.df6, DateUtil.df1);
					createTime = DateUtil.getShowTime(createTime);
					viewHolder.tv_create_time.setText(createTime);
				}else{
					viewHolder.tv_create_time.setText("时间错误");
				}
				byte[] dataByte = Tools.yxReversal(Tools.parseHexStr2Byte(data));
				dataByte = Tools.byteTobyte(dataByte, 13 + 25 + 25 + 15, dataByte.length-(13 + 25 + 25 + 15));

				int num = 0;
				num += 41;

				// 41	上车时间	BCD[5]	格式为YY-MM-DD-hh-mm
				String sTime = Tools.bcd2Str(Tools.byteTobyte(dataByte, num, 5));
				sTime = sTime + "00";
				sTime = DateUtil.getTime(sTime, DateUtil.df8, DateUtil.df12);
				num += 5;
				// 下车时间	BCD[2]	格式为hh-mm
				String eTime = Tools.bcd2Str(Tools.byteTobyte(dataByte, num, 2));
				if(eTime.length() == 3){
					eTime = "0"+eTime;
				}
				eTime = eTime + "00";
				eTime = DateUtil.getTime(eTime, DateUtil.df19, DateUtil.df12);
				num += 2;
				// 计程公里	BCD[3]
				num += 3;
				// 空驶公里	BCD[2]
				num += 2;
				// 附加费	BCD[3]	格式XXXXX.X元
				num += 3;
				// 等待计时时间	BCD[2]	格式为hh-mm
				num += 2;
				// 70	交易金额	BCD[3]	格式XXXXX.X元（总金额）
				BigDecimal decimal = new BigDecimal(Tools.bcd2Str(Tools.byteTobyte(dataByte, num, 3)));
				decimal = decimal.divide(new BigDecimal(10));
				String amount = DecimalUtil.priceFormat(decimal.doubleValue());
				num += 3;
				// 74	当前车次	UINT32
				int carCount = Integer.parseInt(Tools.parseByte2HexStr(Tools.byteTobyte(dataByte, num, 4)), 16);
				num += 4;
				//	78 	账单类型	BYTE
				int payType = Integer.parseInt(Tools.parseByte2HexStr(Tools.byteTobyte(dataByte, num, 1)), 16);
				System.out.println("payType----------------:"+payType);

				viewHolder.tv_empty_time.setText(eTime);
				viewHolder.tv_load_time.setText(sTime);
				viewHolder.tv_car_times.setText(""+carCount);
				viewHolder.tv_amount.setText(amount);
				viewHolder.tv_amount.setTextColor(Color.parseColor("#FEE801"));
				/*if(localInfo.getStatus() == 0){
					//未上传
					viewHolder.tv_amount.setTextColor(Color.parseColor("#FF0000"));
					viewHolder.tv_amount_text.setTextColor(Color.parseColor("#FF0000"));
				}else{
					viewHolder.tv_amount.setTextColor(Color.parseColor("#FEE801"));
					viewHolder.tv_amount_text.setTextColor(Color.parseColor("#FEE801"));
				}*/
				if(payType == 0){
					viewHolder.tv_pay_type.setText("现金");
				}else if(payType == 1){
					viewHolder.tv_pay_type.setText("M1卡");
				}else if(payType == 3){
					viewHolder.tv_pay_type.setText("CPU卡");
				}else if(payType == 9){
					viewHolder.tv_pay_type.setText("其他");
				}
				return convertView;

			} catch (Exception e) {
				AppLog.e(ExceptionUtil.getInfo(e), e);
				e.printStackTrace();
				return null;
			}
		}
	}

	class ViewHolder{
		private TextView tv_empty_time;
		private TextView tv_load_time;
		private TextView tv_car_times;
		private TextView tv_pay_type;
		private TextView tv_amount,tv_amount_text;
		private TextView tv_create_time;
	}

	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub

	}
}
